import User.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet(name = "Register", urlPatterns = "/Register")
public class Register extends HttpServlet{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        doRegister(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {

    }
    protected void doRegister(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{

        String username=request.getParameter("form-username1");
        String email=request.getParameter("form-username2");
        String passwd=request.getParameter("form-password1");
        String passwd2=request.getParameter("form-password2");

        if( Treatment.islegitimate(username, email, passwd, passwd2) ) //判断合法性
        {
            if(Treatment.isRepeat(email))//判断是否重复
            {
                if(Treatment.writeUser(username, email, passwd)) //判断是否写入成功
                {
                    User user = new User(username, email, passwd, null, "userimags/0.jpg");
                    request.getSession().setAttribute("SELF",user);
                    response.sendRedirect("/user.jsp");
                }
                else
                {
                    response.sendRedirect("/error.jsp");
                }
            }
            else
            {
                response.sendRedirect("/error.jsp");
            }
        }
        else
        {
            System.out.println("注册信息不能为空！");
            response.sendRedirect("/error.jsp");
        }
    }
}
